package main.java.com.kfm.control;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;


import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Properties;


public class JdbcSelect {
    private final static String URL = "D:\\kaifamiao\\code\\oct\\servlet\\src\\io\\druld.properties";
    private static DataSource dataSource;
    private static Connection conn = null;
    private static QueryRunner queryRunner = new QueryRunner();

    private static void getDataSource() throws Exception {
        if (dataSource == null) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(URL));
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        }
    }

    public static <E> List<E> selectinfo(E e, String sql) throws Exception {
        getDataSource();
        BeanListHandler<E> listHandler = (BeanListHandler<E>) new BeanListHandler<>(e.getClass());
        List<E> query = queryRunner.query(dataSource.getConnection(), sql, listHandler);
        close();
        return query;
    }

    public static void insertInfoLogs(String str) throws Exception {
        getDataSource();
        //获取当前时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String parse = simpleDateFormat.format(System.currentTimeMillis());
        String sql = "insert into logsta(control_type, create_DataTime) value (?,?)";
        Object[] params = {str, parse};
        conn = dataSource.getConnection();
        queryRunner.update(conn, sql, params);
    }
    //查询数据
    public static void insertiofo(String sql, Object... objects) throws Exception {
        getDataSource();
        conn=dataSource.getConnection();
        queryRunner.update(conn, sql, objects);
    }

    public static void close() throws SQLException {
        if (conn != null) {
            conn.close();
            conn = null;
        }
    }
//    public static void main(String[] args) throws Exception {
//        String sql3 = "select * from logsta";
//        List<LogsTA> selectinfo3 = selectinfo(new LogsTA(), sql3);
//        for (LogsTA logsTA : selectinfo3) {
//            System.out.println(logsTA);
//        }
//    }
}

